package drds.data_propagate.driver.packets.server;

import drds.data_propagate.driver.packets.AbstractPacket;
import drds.data_propagate.driver.utils.ByteHelper;
import lombok.Getter;
import lombok.Setter;

import java.io.IOException;

/**
 * Aka. OK packet
 *
 * @author fujohnwang
 */
public class OkPacket extends AbstractPacket {
    @Setter
    @Getter
    public byte fieldCount;
    @Setter
    @Getter
    public byte[] affectedRows;
    @Setter
    @Getter
    public byte[] insertId;
    @Setter
    @Getter
    public int serverStatus;
    @Setter
    @Getter
    public int warningCount;
    @Setter
    @Getter
    public String message;

    /**
     * <pre>
     *  VERSION 4.1
     *  Bytes                       Name
     *  -----                       ----
     *  1   (Length Coded Binary)   field_count, always = 0
     *  1-9 (Length Coded Binary)   affected_rows
     *  1-9 (Length Coded Binary)   insert_id
     *  2                           server_status
     *  2                           warning_count
     *  n   (until end of packet)   message
     * </pre>
     *
     * @throws IOException
     */
    public void decode(byte[] data) throws IOException {
        int index = 0;
        // 1. read field count
        this.fieldCount = data[0];
        index++;
        // 2. read affected rows
        this.affectedRows = ByteHelper.readBinaryCodedLengthBytes(data, index);
        index += this.affectedRows.length;
        // 3. read insert id
        this.insertId = ByteHelper.readBinaryCodedLengthBytes(data, index);
        index += this.insertId.length;
        // 4. read server status
        this.serverStatus = ByteHelper.readUnsignedShortLittleEndian(data, index);
        index += 2;
        // 5. read warning count
        this.warningCount = ByteHelper.readUnsignedShortLittleEndian(data, index);
        index += 2;
        // 6. read message.
        this.message = new String(ByteHelper.readFixedLengthBytes(data, index, data.length - index));
        // end read
    }

    public byte[] encode() throws IOException {
        return null;
    }


}
